const Koa = require("koa");
const render = require("koa-ejs"); //ejs编译器
const router = require("koa-router")();
const path = require("path");
const koaStatic = require("koa-static");
const koaBody = require("koa-body");
const cors = require("koa2-cors");
const koajwt = require("koa-jwt");
const jsonwebtoken = require("jsonwebtoken");
const mongoConf = require("./config/mongo");
const formatresponse = require("./middleware/formatresponse");
const fs = require("fs");
const $config = require("../config");

const app = new Koa();
const SECRET = "nideXingege";

app.use(
	cors({
		origin: function () {
			//origin: function(ctx) {
			// const whiteList = ["http://192.168.88.169:5566/", "http://192.168.88.38:5566/"]; //可跨域白名单
			// let url = ctx.header.referer.substr(0, ctx.header.referer.length - 1);
			// if (whiteList.includes(url)) {
			// 	return url; //注意，这里域名末尾不能带/，否则不成功，所以在之前我把/通过substr干掉了
			// }
			// return "http://localhost::5566"; //默认允许本地请求3000端口可跨域
			return "*";
		},
		maxAge: 5, //指定本次预检请求的有效期，单位为秒。
		credentials: true, //是否允许发送Cookie
		allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], //设置所允许的HTTP请求方法
		allowHeaders: ["Content-Type", "Authorization", "Accept"], //设置服务器支持的所有头信息字段
		exposeHeaders: ["WWW-Authenticate", "Server-Authorization"], //设置获取其他自定义字段
	})
);

app.use(koaStatic(__dirname + "/public"));

app.use(
	koaBody({
		multipart: true,
		formidable: {
			maxFileSize: 3000 * 1024 * 1024,
		},
	})
);

render(app, {
	root: path.join(__dirname, "views"),
	layout: false,
	viewExt: "html",
	cache: false,
	debug: false,
});
//路由白名单
// if (
// 	process.argv.slice(2).length > 0 &&
// 	process.argv.slice(2)[0] === "--production"
// ) {
app.use(
	koajwt({ secret: SECRET }).unless({
		path: [
			/^\/common\/html2canvas\/corsproxy/,
			/^\/project\/view/,
			/^\/project\/verify/,
			/^\/auth\/login/,
			/^\/auth\/register/,
			/^\/connection\/excuteSql/,
			/^\/upload_static\/images/,
			/^\/auth\/getalluser/,
		],
	})
);
//}

router.use(async (ctx, next) => {
	let token = ctx.headers.authorization;
	if (token) {
		ctx.state.user = jsonwebtoken.verify(
			token.split(" ")[1],
			SECRET
			// (error, decoded) => {
			// 	if (error) {
			// 		console.log("error",error);
			// 		console.log("decoded",decoded);
			// 		return;
			// 	}
			// 	console.log("验证成功",decoded);
			// }
		);
	}
	ctx.state.BASE_URL = $config.baseURL;
	ctx.state.ROOT_PATH = path.join(__dirname, "../");
	ctx.state.SERVER_PATH = path.join(__dirname, "./");
	ctx.state.SECRET = SECRET;
	await next();
});

mongoConf.connect();

fs.readdirSync(path.join(__dirname, "./routes")).forEach((route) => {
	let api = require(`./routes/${route}`);
	router.use(`/${route.replace(".js", "")}`, api.routes());
});

app.use(formatresponse);

app.use(router.routes());
app.use(router.allowedMethods());

app.listen($config.port);

console.log("监听端口" + $config.port);
